package com.neu.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.neu.App;
import com.neu.MainActivity;
import com.neu.R;
import com.neu.bean.ResultBean;
import com.neu.util.RetrofitClient;
import com.neu.util.RetrofitUtil;

import java.util.HashMap;
import java.util.Map;

import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText txtUser;
    private EditText txtPwd;
    private Button btnSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }


    private void initView() {
        txtUser = (EditText) findViewById(R.id.txtUser);
        txtPwd = (EditText) findViewById(R.id.txtPwd);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);

        btnSubmit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnSubmit:
                submit();
                break;
        }
    }

    private void submit() {
        // validate
        String txtUserString = txtUser.getText().toString().trim();
        if (TextUtils.isEmpty(txtUserString)) {
            Toast.makeText(this, "txtUserString不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String txtPwdString = txtPwd.getText().toString().trim();
        if (TextUtils.isEmpty(txtPwdString)) {
            Toast.makeText(this, "txtPwdString不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        //登录
        checkLogin(txtUserString,txtPwdString);

    }

    private void checkLogin(String txtUserString, String txtPwdString) {
        String url="/prod-api/api/login";
        Map<String,Object> param=new HashMap<>();
        param.put("username",txtUserString);
        param.put("password",txtPwdString);
        new RetrofitClient().post(url, param, new RetrofitClient.BackJson() {
            @Override
            public void success(String json) {
                ResultBean result=new Gson().fromJson(json,ResultBean.class);
                if(result.getCode()==200){
                    Intent intent=new Intent(LoginActivity.this, MainActivity.class);
                    RetrofitUtil.token=result.getToken();
                    startActivity(intent);
                    finish();
                }else{
                    Toast.makeText(App.context,"登录失败",Toast.LENGTH_LONG).show();
                }

            }
        });

    }
}